package com.chen.androidstudy.utils

import android.annotation.SuppressLint
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.ceil

object DateUtils {
    const val YYYY_MM_dd = "yyyy-MM-dd"
    const val YYYY_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss"
    const val YYYY_MM_dd_HH_mm = "yyyy-MM-dd HH:mm"

    @SuppressLint("SimpleDateFormat")
    fun parseTime(time: String, format: String = YYYY_MM_dd): String {
        val date = parseDate(time, format)
        val simpleDateFormat = SimpleDateFormat(format)
        return simpleDateFormat.format(date)
    }

    @SuppressLint("SimpleDateFormat")
    fun parseDate(time: String, format: String = YYYY_MM_dd): Date {
        val simpleDateFormat = SimpleDateFormat(format)
        return simpleDateFormat.parse(time.replace("T", " "))
    }

    /**
     * 获取当前时间与指定时间相差多少天
     */
    @SuppressLint("SimpleDateFormat")
    fun getRangeDays(time: String): Long {
        return try {
            val dft: DateFormat = SimpleDateFormat(YYYY_MM_dd_HH_mm_ss)
            val startDate: Date = dft.parse(time) //结束时间
            val starTime: Long = startDate.time
            val endTime: Long = Date().time
            val num = endTime - starTime //时间戳相差的毫秒数
            ceil(num / 24 / 60 / 60 / 1000f).toLong()
        } catch (e: ParseException) {
            e.printStackTrace()
            0
        }
    }

    /**
     * 获取当前日期
     */
    fun getCurrentDate(): String {
        val simpleDateFormat = SimpleDateFormat(YYYY_MM_dd_HH_mm_ss)
        return simpleDateFormat.format(Date())
    }
}